<template>
	<view class="defect-type-picker row full-width input">
		<picker class="flex1 input-text" @change="handlePickerChange" :value="activeIndex" range-key="itemName" :range="list">
			<text v-if="isShowClearButton" class="full-width input-text">{{activeTypeName}}</text>
			<text v-else class="full-width input-text placeholder">{{placeholderText}}</text>
		</picker>
		<uni-icons class="flex-shrink0" v-show="isShowClearButton" type="clear" size="25" color="#c0c4cc" @click="handleResetClick"></uni-icons>
	</view>
</template>

<script>
	export default {
		name: 'DefectTypePicker',
		model: {
			prop: 'defectType',
			event: 'input'
		},
		data() {
			return {
				activeIndex: null
			}
		},
		props: {
			defectType: {
			  type: String,
			  default: null
			},
			typeList: {
				type: Array,
				default: ()=>[]
			},
			labelName: {
				type: String,
				default: 'value'
			},
			placeholder: {
				type: String,
				default: null
			}
		},
		computed: {
			/** 选择的类型名称显示名称 */
			activeTypeName: function() {
				const defectType = (this.activeIndex>=0 && this.typeList.length>0)?this.list[this.activeIndex]:null;
				return defectType?defectType.itemName:'';
			},
			/** 可选择的类型集合 */
			list() {
				return this.typeList.map(t=>{
					t.itemName = this.$i18n.t(t[this.labelName]);
					return t;
				})
			},
			/** 是否显示清空按钮  */
			isShowClearButton() {
				return this.typeList.length>0 && this.activeTypeName;
			},
			/** placeholder显示文本  */
			placeholderText() {
				return this.placeholder || this.$i18n.t('defect.select-type');
			}
		},
		methods: {
			/** 重设 */
			handleResetClick(e) {
				this.activeIndex = -1;
				this.emit();
			},
			/**处理等级选择改变 */
			handlePickerChange(e) {
				this.activeIndex = e.detail.value;
				this.emit();
			},
			/** 更新父组件传递的v-model */
			emit() {
				if(this.activeIndex>=0 && this.typeList.length>0) {
					this.$emit('input', this.typeList[this.activeIndex][this.labelName]);
				} else {
					this.$emit('input', null);
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.defect-type-picker {
		justify-content: flex-end;
		padding-left: 20rpx;
	}
	.input-text {
		min-height: 28rpx;
	}
</style>